<template>
  <div class="table">
    <div class="table_top">
      <div class="table_top_L">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="比赛id">
            <el-input v-model="formInline.id" placeholder="比赛id"></el-input>
          </el-form-item>
          <el-form-item label="比赛状态">
            <el-select v-model="formInline.state" placeholder="审核状态" clearable>
              <el-option label="未开始" value="0"></el-option>
              <el-option label="已开始" value="1"></el-option>
              <el-option label="已结束" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="联赛id">
            <el-select v-model="formInline.contestId" placeholder="联赛id" clearable filterable>
              <el-option v-for="option in tableData1" :key="option.value" :label="option.label" :value="option.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="inquire">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <el-table
      :data="tableData"
      width="10%"
      height="100%"
      border
      stripe
      highlight-current-row
      v-loading="listLoading"
      ref="table"
      current-row-key="id"
      row-key="id"
      key="id"
      column-key="id"
      @selection-change="selectionChange"
    >
      <el-table-column prop="id" label="比赛id" width="60"> </el-table-column>
      <el-table-column prop="oneTeam.teamName" label="主队名称"> </el-table-column>
      <el-table-column prop="twoTeam.teamName" label="客队名称"> </el-table-column>
      <el-table-column prop="tournamentBeginTime" label="比赛开始时间" width="140"> </el-table-column>
      <el-table-column prop="state" label="审核状态" width="80">
        <template v-slot:default="{ row }">
          <el-tag :type="row.state == 0 ? 'info' : row.state == 1 ? 'success' : row.state == 2 ? 'danger' : 'info'">
            {{ row.state == 0 ? '未开始' : row.state == 1 ? '已开始' : row.state == 2 ? '已结束' : '--' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="视频地址" width="70">
        <template v-slot:default="{ row }">
          <el-button type="text" @click="fetchVideoList(row.id)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="大屏幕链接" width="80">
        <template v-slot:default="{ row }">
          <div style="display: flex;align-items: center;">
            <el-button type="text" @click="openLink(row.threeUrl)">3v3</el-button>
            <el-button type="text" @click="openLink(row.fiveUrl)">5v5</el-button>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="编辑" width="120">
        <template v-slot:default="{ row }">
          <el-button type="text" @click="updateRow(row.id)">设置</el-button>
          <!-- <el-button type="text" @click="pushFlow(row)">推流</el-button> -->
          <el-button type="text" @click="rePlay(row)">复制即时回放</el-button>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="del(0, scope.row.id)" type="info" plain size="small">
            未开始
          </el-button>
          <el-button type="success" plain size="small" @click="del(1, scope.row.id)">
            已开始
          </el-button>
          <el-button type="danger" plain size="small" @click="del(2, scope.row.id)">
            已结束
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="视频列表" :visible.sync="videoDialogVisible" width="50%">
      <el-table :data="videoList">
        <el-table-column prop="name" label="视频名称" width="80"> </el-table-column>
        <el-table-column prop="videoUrl" label="视频地址"> </el-table-column>
        <el-table-column label="视频地址" width="70">
          <template v-slot:default="{ row }">
            <el-button type="text" @click="copyUrl(row.videoUrl)">复制</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <el-dialog title="设置信息" :visible.sync="updateVisible" width="50%">
      <el-form label-width="120px" :model="formData" class="demo-form-inline">
        <el-form-item label="赛事名称">
          <el-input v-model="formData.tournamentName" style="width: 50%;"></el-input>
        </el-form-item>
        <el-form-item label="赛事开始时间">
          <el-date-picker
            v-model="formData.tournamentBeginTime"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择日期时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="比赛类型">
          <el-select v-model="formData.type">
            <el-option label="小组赛" :value="1"></el-option>
            <el-option label="淘汰赛" :value="2"></el-option>
            <el-option label="四强赛" :value="3"></el-option>
            <el-option label="半决赛" :value="4"></el-option>
            <el-option label="决赛" :value="5"></el-option>
            <el-option label="季军赛" :value="6"></el-option>
            <el-option label="排位赛" :value="7"></el-option>
            <el-option label="常规赛" :value="8"></el-option>
            <el-option label="季后赛" :value="9"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比赛阶段备注">
          <el-input type="textarea" :rows="3" v-model="formData.typeRemake" style="width: 50%;"></el-input>
        </el-form-item>
        <el-form-item label="比赛地点">
          <el-input v-model="formData.address" style="width: 50%;"></el-input>
        </el-form-item>
        <el-form-item label="统计模式">
          <el-select v-model="formData.statisticsModel">
            <el-option label="标准" :value="1"></el-option>
            <el-option label="进阶" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="观赛人数">
          <el-input type="number" v-model="formData.liveNum" style="width: 50%;"></el-input>
        </el-form-item>
        <el-form-item label="是否开启聊天">
          <el-select v-model="formData.chatFlag">
            <el-option label="是" :value="0"></el-option>
            <el-option label="否" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="比分条开关">
          <el-select v-model="formData.equipmentSwitch">
            <el-option label="关" :value="0"></el-option>
            <el-option label="开" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视频分切间隔时间单位s">
          <el-input-number v-model="formData.timeInterval" style="width: 30%;"></el-input-number>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updateSubmit">保存</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- <shareLive ref="shareLiveRef"></shareLive> -->
    <el-dialog title="即时回放" :visible.sync="replayVisible" width="50%" @close="closePlay">
      <div>
        <!-- 设置播放器容器 -->
        <video ref="videoPlayer" controls autoplay muted width="800" height="450"></video>
        <div>
          <p>直播回看操作面板</p>
          <div style="margin-right: 20px;">单位：秒</div>
          <el-slider v-model="value1" :min="90" :max="1200" @change="sliderChange"></el-slider>
          <div>当前移动的时间：{{ value1 }}s</div>
        </div>
      </div>
    </el-dialog>

    <div class="table_bottom">
      <el-pagination @current-change="paginationChange" small background layout="prev, pager, next" :total="total" :page-size="20">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import Hls from 'hls.js'
// import shareLive from './shareLive.vue'
import { tournamentInfo, tournamentStatusPost, livePlayList, tournamentGet, contestListDown } from '../../api/table.js'
export default {
  data() {
    return {
      hls: null,
      //
      value1: 90,
      videoId: '', // 视频Id
      playUrl: '', //视频地址
      TCPlayer: null, //放入全局
      //
      tableData1: [],
      tableData: [],
      listLoading: true,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formInline: {
        id: '',
        contestId: '',
        state: ''
      },
      total: 0, // 添加总条数
      videoDialogVisible: false, // 控制视频弹窗的显示与隐藏
      videoList: [], // 存储视频列表数据
      formData: {},
      updateVisible: false,
      //
      replayVisible: false,
      deepUrl: ''
    }
  },
  mounted() {
    this.reqData1()
    this.tableData = this.reqData()
    this.listLoading = false
  },
  beforeDestroy() {
    this.TCPlayer = null // 销毁播放器实例，释放资源

    if (this.hls) {
      this.hls.destroy() // 销毁 Hls 实例，避免内存泄漏
    }
  },
  methods: {
    initHlsPlayer() {
      const video = this.$refs.videoPlayer

      if (Hls.isSupported()) {
        this.hls = new Hls()
        this.hls.loadSource(this.playUrl)
        this.hls.attachMedia(video)
        this.hls.on(Hls.Events.MANIFEST_PARSED, () => {
          video.play()
        })
      } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        // 如果浏览器原生支持 HLS（如 Safari）
        video.src = this.playUrl
        video.addEventListener('loadedmetadata', () => {
          video.play()
        })
      }
    },
    closePlay() {
      console.log('测试')
      this.TCPlayer = null // 销毁播放器实例，释放资源
    },
    sliderChange() {
      this.playUrl = this.deepUrl + '&txTimeshift=on&tsDelay=' + this.value1
      // this.TCPlayer.src(this.playUrl)
      this.initHlsPlayer()
    },
    //
    pushFlow(row) {
      this.$refs.shareLiveRef.openDialog(row)
    },
    rePlay(row) {
      // //1756
      let str = `http://m.yundongshugenmatch.cn/#/pages/playback?id=${row.id}`
      this.$copyText(str)
        .then(() => {
          this.$message.success({ message: '已成功复制即时回放地址' })
        })
        .catch(() => {
          this.$message.error({ message: '复制失败' })
        })

      // 以下功能是弹窗播放直播流视频 已实现
      // this.replayVisible = true
      // this.formData = row
      // gettournamentLive({ tournamentId: row.id }).then(res => {
      //   console.log(res, 'roew--------')
      //   this.deepUrl = JSON.parse(JSON.stringify(res.rows[0].viewUrl))
      //   this.playUrl = this.deepUrl + '&txTimeshift=on&tsDelay=90'
      //   this.initHlsPlayer()
      // })
    },
    //
    openLink(link) {
      window.open(link, '_blank')
    },
    updateRow(id) {
      tournamentGet({ id: id }).then(res => {
        console.log(res, 'roew--------')
        this.updateVisible = true
        this.formData = res.data
      })
    },
    updateSubmit() {
      // let params = {
      //   id: this.formData.id
      // }
      tournamentStatusPost(this.formData).then(res => {
        if (res.code == 200) {
          this.$message({
            type: 'success',
            message: `设置成功!`
          })
          this.updateVisible = false
        }
      })
    },
    fetchVideoList(id) {
      livePlayList({ tournamentId: id }).then(res => {
        console.log(res.rows, 'roew--------')
        this.videoList = res.rows
        this.videoDialogVisible = true
      })
    },
    copyUrl(url) {
      navigator.clipboard.writeText(url).then(() => {
        this.$message.success('地址已复制')
      })
    },
    inquire() {
      this.reqData(1, 20, {
        id: this.formInline.id,
        state: this.formInline.state,
        contestId: this.formInline.contestId
      })
    },
    selectionChange(selection) {
      this.selectionLength = selection.length
    },
    handleClick(row) {
      this.dialogTitle = row ? '修改' : '新增'
      this.dialogFormVisible = true
    },
    // 分切改变，返回页码
    paginationChange(page) {
      this.listLoading = true
      this.reqData(page, 20, this.formInline) // 传入当前页码和每页显示的数据量
      this.$nextTick(() => {
        this.listLoading = false
        this.$refs.table.bodyWrapper.scrollTop = 0
      })
    },
    // 请求
    reqData(pageNum = 1, pageSize = 20, query = {}) {
      const params = { pageNum, pageSize, ...query }
      tournamentInfo(params).then(res => {
        this.tableData = res.rows
        this.total = res.total // 设置总条数
      })
    },
    reqData1(pageNum = 1, pageSize = 10000, query = {}) {
      console.log(query, 'query======')
      const params = { pageNum, pageSize, ...query }
      contestListDown(params).then(res => {
        //tableInfo
        this.tableData1 = res.data.map(item => ({
          value: item.id,
          label: item.name // 假设 id 是数字类型
        }))
      })
    },
    del(state, id) {
      const data = {
        id: id,
        state: state
      }
      let statusMessage
      if (state === 0) {
        statusMessage = '未开始'
      } else if (state === 1) {
        statusMessage = '已开始'
      } else if (state === 2) {
        statusMessage = '已结束'
      }

      this.$confirm(`比赛状态更改为${statusMessage}, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          tournamentStatusPost(data).then(res => {
            console.log(res, 'res=======----')
            this.$message({
              type: 'success',
              message: `状态更改为${statusMessage}成功!`
            })
            this.reqData(1, 20, this.formInline)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    }
  }
}
</script>

<style lang="scss" scoped>
.table {
  display: flex;
  flex-flow: column;
  box-sizing: border-box;
  .table_top {
    display: flex;
    justify-content: space-between;
    padding-bottom: 10px;
    .table_top_L {
      text-align-last: left;
      flex: 1;
      overflow: hidden;
    }
  }
  .table_bottom {
    margin-top: 10px;
  }
  height: 100%;
}
</style>
<style>
.table .el-table {
  transition: all ease-in-out 0.3s;
}
.table .el-table td,
.table .el-table th {
  text-align: center;
}
.table .el-dialog {
  text-align: left;
}
.table .el-dialog .line {
  text-align: center;
}
.el-image-viewer__close {
  background-color: #fff;
}
/* 重新覆盖原来的样式，原来的样式是.el-drawer获取焦点时的outline */
.el-image-viewer__wrapper:focus {
  outline: none;
}
</style>
